import vue from 'vue'
import vuex from 'vuex'

vue.use(vuex)

export default new vuex.Store({
  state: {
    todoList: [],
    select: 1,
  },
  mutations: {
    ADDTODO(state, todo) {
      const todoObj = {
        todo,
        state: false,
      }
      state.todoList.push(todoObj)
    },
    CHANGESTATE(state, index) {
      state.todoList[index].state = !state.todoList[index].state
    },
    SET_SELECT(state, value) {
      state.select = value
    },
    DELETE_DONE(state) {
      state.todoList = state.todoList.filter(item => !item.state)
    },
    CHOOSE_DELETE(state, index) {
      state.todoList.splice(index, 1)
    }
  },
  actions: {
    changeState(context, index) {
      const select = context.state.select
      if (select === 1) {
        context.commit('CHANGESTATE', index)
      } else if (select === 2) {
        context.commit('CHANGESTATE', context.getters.undoneIndex[index])
      } else if (select === 3) {
        context.commit('CHANGESTATE', context.getters.doneIndex[index])
      }
    },
    chooseDelete(context, index) {
      const select = context.state.select
      if (select === 1) {
        context.commit('CHOOSE_DELETE', index)
      } else if (select === 2) {
        context.commit('CHOOSE_DELETE', context.getters.undoneIndex[index])
      } else if (select === 3) {
        context.commit('CHOOSE_DELETE', context.getters.doneIndex[index])
      }
    }
  },
  getters: {
    done(state) {
      return state.todoList.filter(item => {
        return item.state
      })
    },
    undone(state) {
      return state.todoList.filter(item => {
        return !item.state
      })
    },
    doneIndex(state) {
      const arr = []
      state.todoList.forEach((item, index) => {
        if (item.state) {
          arr.push(index)
        }
      })
      return arr
    },
    undoneIndex(state) {
      const arr = []
      state.todoList.forEach((item, index) => {
        if (!item.state) {
          arr.push(index)
        }
      })
      return arr
    }
  }
})